package com.healthcarex.hip.saas.message.handler;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;


public class DateValueHandler extends AbstractValueHandler {
    private static final Logger logger = LoggerFactory
            .getLogger(DateValueHandler.class);

    private static final String[] DATE_PATTERN = new String[]{
            "yyyyMMddHHmmss", "yyyyMMdd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd"};

    @Override
    public Object getReadingValue(Object srcValue, String destType,
                                  String destFormat) {
        // List<String> patternList = Arrays.asList(_defaultPatterns);

        // if (!patternList.contains(destFormat)) {
        // patternList.add(0, destFormat);
        // }

        List<String> patternList = new ArrayList<String>();
        patternList.add(destFormat);

        try {
            return DateUtils.parseDate((String) srcValue,
                    patternList.toArray(new String[]{}));
        } catch (ParseException e) {
            logger.error(e.toString());
        }

        return srcValue;
    }

    @Override
    public String getWritingValue(Object srcValue, String destFormat) {
        if (srcValue instanceof Date) {
            return DateFormatUtils.format((Date) srcValue, destFormat);
        }

        return srcValue.toString();
    }

    @Override
    public void getNodeValue(Node node, Field field, Object obj) throws Exception {
        String value = node.getTextContent();
        // 使用DateUtils类转换
        field.set(obj, DateUtils.parseDate(value, DATE_PATTERN));
    }

    @Override
    public void updateNodeValue(Node node, Field field, Object obj) throws Exception {
        Object value = field.get(obj);
        if (value == null) {
            node.setTextContent("");
        } else {
            node.setTextContent(String.valueOf(value));
        }
    }

    @Override
    public void setNodeValue(Node node, Field field, Object obj) throws Exception {

    }
}
